package cn.zhihong.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDate;

/**
 * @ClassName MyMetaObjectHandler
 * @Author 庄志宏
 * @Date 2022/4/21 23:36
 * 自定义元数据对象处理器
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]====");
        log.info(metaObject.toString());
        //在普通类中获取session
        HttpSession session = GetSession.getSession();
        Long empId= (Long) session.getAttribute("employee");
        if (empId !=null){
            metaObject.setValue("createTime", LocalDate.now());
            metaObject.setValue("createUser",empId);
            metaObject.setValue("updateTime",LocalDate.now());
            metaObject.setValue("updateUser",empId);
        }
        Long userId = (Long) session.getAttribute("user");
        if (userId != null){
            metaObject.setValue("createTimeCline", LocalDate.now());
            metaObject.setValue("createUserCline",userId);
            metaObject.setValue("updateTimeCline",LocalDate.now());
            metaObject.setValue("updateUserCline",userId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]====");
        log.info(metaObject.toString());
        HttpSession session = GetSession.getSession();
        Long empId= (Long) session.getAttribute("employee");
        log.info("保存在session中的用户id：" + empId);
        if (empId !=null){
            metaObject.setValue("updateTime",LocalDate.now());
            metaObject.setValue("updateUser",empId);
        }
        Long userId = (Long) session.getAttribute("user");
        if (userId != null){
            metaObject.setValue("updateTimeCline",LocalDate.now());
            metaObject.setValue("updateUserCline",userId);
        }

    }
}
